import * as fs from 'fs'
import * as path from 'path'
import { Singleton, AutoWired } from 'typescript-ioc'
// 插件根目录
const PLUGIN_DIR = 'public/plugins'

// @AutoWired
@Singleton
export class PluginService {
  // 插件列表
  private pluginList: any[]

  constructor() {
    this.pluginList = this.findPluginList()
  }

  /**
   * 获取插件列表
   */
  private getPlugins() {
    const dirs = fs.readdirSync(path.resolve(PLUGIN_DIR))
    return dirs.map(dir => path.join(PLUGIN_DIR, dir)).filter(dir => fs.statSync(dir).isDirectory())
  }

  /**
   * 获取配置信息
   * @param plugin 插件目录
   */
  private getPluginConfig(plugin) {
    return require(path.resolve(plugin, 'assets', 'config.json'))
  }

  /**
   * 验证配置是否存在
   * @param plugin 插件目录
   */
  private existPluginConfig(plugin) {
    return fs.existsSync(path.resolve(plugin, 'assets', 'config.json'))
  }

  /**
   * 排序配置
   * @param x 插件目录
   * @param y 插件目录
   */
  private sortPluginConfig(x, y) {
    return x.pluginOrder - y.pluginOrder
  }

  /**
   * 查询插件列表
   */
  public findPluginList() {
    return this.getPlugins()
      .filter(this.existPluginConfig)
      .map(this.getPluginConfig)
      .sort(this.sortPluginConfig)
  }

  /**
   * 获取插件列表
   */
  public getPluginList() {
    if (this.pluginList && this.pluginList.length) {
      return this.pluginList
    } else {
      this.pluginList = this.findPluginList()
    }

    return this.pluginList
  }
}
